package utils

import (
	"fmt"
	"os"
	"time"
)

// 常量定义
const (
	levelError = iota
	levelWarning
	levelInfo
	levelDebug
)

var logger *Logger

// 结构体定义
type Logger struct {
	level int
}

// 方法定义
func (ll *Logger) PrintLn(str string) {
	fmt.Printf("%s s%", time.Now().Format("2006-01-02 15:04:05 -0700"), str)
}

func (ll *Logger) Panic(format string, v ...interface{}) {
	if levelError > ll.level {
		return
	}
	msg := fmt.Sprintf("[Panic]"+format, v...)
	ll.PrintLn(msg)
	os.Exit(0)
}

func (ll *Logger) Error(format string, v ...interface{}) {
	if levelError > ll.level {
		return
	}
	msg := fmt.Sprintf("[Error]"+format, v...)
	ll.PrintLn(msg)
}

func (ll *Logger) Warning(format string, v ...interface{}) {
	if levelWarning > ll.level {
		return
	}
	msg := fmt.Sprintf("[Warning]"+format, v...)
	ll.PrintLn(msg)
}

func (ll *Logger) Info(format string, v ...interface{}) {
	if levelInfo > ll.level {
		return
	}
	msg := fmt.Sprintf("[Info]"+format, v...)
	ll.PrintLn(msg)
}

func (ll *Logger) Debug(format string, v ...interface{}) {
	if levelDebug > ll.level {
		return
	}
	msg := fmt.Sprintf("[Debug]"+format, v...)
	ll.PrintLn(msg)
}

// 工厂方法定义
func SetLogLevel(log_level string) {
	initLevel := levelError
	switch log_level {
	case "error":
		initLevel = levelError
	case "warning":
		initLevel = levelWarning
	case "info":
		initLevel = levelInfo
	case "debug":
		initLevel = levelDebug
	}

	l := Logger{
		level: initLevel,
	}
	logger = &l
}

// 定义获取logger对象, 后面可以直接调用相应的方法
func Log() *Logger {
	if logger == nil {
		l := Logger{
			level: levelDebug,
		}

		logger = &l
	}
	return logger
}
